package com.heartech.prediciton_wx.controller.qrstr;


import com.heartech.prediciton_wx.constant.WxCode;
import com.heartech.prediciton_wx.service.qrcode.QrCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Slf4j
@RestController
@RequestMapping("/wxpublic")
public class UpdataStrController {

    @Autowired
    private QrCodeService qrCodeService;

    @PostMapping("/update_str")
    public ResponseEntity<String> updateStr(@RequestParam String random_str, @RequestParam int state) {
        String url = WxCode.update_str;
        String postParams = "random_str=" + URLEncoder.encode(random_str, StandardCharsets.UTF_8) +
                "&state=" + URLEncoder.encode(String.valueOf(state), StandardCharsets.UTF_8);

        try {
            String response = qrCodeService.sendPostRequest(url, postParams);
            if (response != null) {
                return ResponseEntity.ok(response);
            } else {
                log.error("POST request did not work for random_str: {}", random_str);
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("POST request not worked");
            }
        } catch (Exception e) {
            log.error("Exception occurred during POST request", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
        }
    }
}

